package com.jh.complicate.netty.buffer;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author Administrator
 * @projectName newforward
 * @title MappedBufferDemo.java
 * @package com.jh.complicate.netty.buffer
 * @description 内存映射
 * @date 2019/6/24 00:02
 */
public class MappedBufferDemo {

    private final static int start = 0;
    private final static int size = 1024;

    public static void main(String[] args) throws Exception{
        // 以读写方式打开文件
        RandomAccessFile raf = new RandomAccessFile("D://test.txt", "rw");
        // 获取管道
        FileChannel fc = raf.getChannel();

        // 把缓冲区跟文件系统进行一个映射关系
        // 只要操作缓冲区里面的内容，文件内容也会跟着改变
        MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, start, size);

        // 更改内容
        mbb.put(0, (byte) 97);
        mbb.put(1023, (byte) 122);

        // 关闭
        raf.close();
    }
}
